import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import {
  COMMAND_PRIORITY_EDITOR,
  createCommand,
  type LexicalCommand,
} from "lexical";
import { useEffect } from "react";

export const UPDATE_EDITOR_CONTENT_COMMAND: LexicalCommand<string> =
  createCommand("UPDATE_EDITOR_CONTENT_COMMAND");

export function ExternalUpdatePlugin() {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    return editor.registerCommand(
      UPDATE_EDITOR_CONTENT_COMMAND,
      (value: string) => {
        const parsed = editor.parseEditorState(value);
        editor.setEditorState(parsed);
        return true;
      },
      COMMAND_PRIORITY_EDITOR,
    );
  }, [editor]);

  return null;
}
